<?php
namespace Library\db;

use Library\Connection;
use Library\Config;

class Db extends Connection
{
	protected $tableName;

	protected $whereValue="";
	
	protected $fieldValue = "*";
	
	protected $sql;
	
	protected $page = "";
	
	protected $prefix = "";

    public function __construct($tableName){
		$this->prefix = Config::get("Config","prefix");
		$this->tableName = $this->prefix.$tableName;
		return $this;
    }

	//	设置表名
	public function table(string $tableName){
		$this->tableName = $this->prefix.$tableName;
		return $this;
	}

	//	构造查询条件
	public function where(array $where=[]){
		if ( empty($where) ){
			echo "where参数不能为空";
			exit;
		}
		$whereSql = "where ";
		$keyArray = array_keys($where);
		for ( $i=0;$i<count($where);$i++ ){
			if ( $i<count($where)-1 ){
				$whereSql=$whereSql.$keyArray[$i]."=".$where[$keyArray[$i]]." and ";
			}else{
				$whereSql=$whereSql.$keyArray[$i]."=".$where[$keyArray[$i]]." ";
			}
		}
		$this->whereValue = $whereSql;
		return $this;
	}

	//	数据集
	public function select(){
		$this->sql = "select ".$this->fieldValue." from ".$this->tableName." ".$this->whereValue.$this->page;
		return $this->query($this->sql);
	}
	
	//	指定字段
	public function field(array $field){
		$this->fieldValue = "";
		for ( $i=0;$i<count($field);$i++ ){
			if ( $i<count($field)-1 ){
				$this->fieldValue = $this->fieldValue." ".$field[$i].",";
			}else{
				$this->fieldValue = $this->fieldValue." ".$field[$i]." ";
			}
		}
		return $this;
	}
	
	//	单行
	public function find(){
		if (strlen($this->whereValue)<1){
			echo "where条件不能为空";
			exit;
		}
		$this->sql = "select ".$this->fieldValue." from ".$this->tableName." ".$this->whereValue;
		$res = $this->query($this->sql);
		return $res[0];
	}
	
	//	单值
	public function value(string $value=""){
		if ($this->fieldValue!="*"){
			echo "filed方法查询与单值value方法冲突!";
			exit;
		}
		if ( strlen($value)<1 ){
			echo "value不能为空";
			exit;
		}
		$this->fieldValue = $value." ";
		$this->sql = "select ".$this->fieldValue." from ".$this->tableName." ".$this->whereValue;
		$res = $this->query($this->sql);
		return $res[0][$value];
	}
	
	//	汇总查询
	public function query($sql){
		$Connection = new Connection();
		$res = $Connection->query($sql);
		$Connection->close();
		return $res;
	}
	
	//	分页
	public function page($page,$num){
		$this->page = " limit ".($page-1)*$num.",".$num." ";
		return $this;
	}
}
?>